<template>
  <div class="doctor-department">
    <!-- 1. 页面标题区 -->
    <div class="page-header">
      <el-button type="text" icon="el-icon-arrow-left" @click="$router.go(-1)">Back</el-button>
      <h2>科室管理</h2>
    </div>
    
    <!-- 2. 搜索和操作区 -->
    <div class="action-bar">
      <!-- 搜索框 -->
      <div class="search-group">
        <el-input 
          v-model="searchKey" 
          placeholder="搜索科室名称" 
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearchClear"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 操作按钮 -->
      <div class="button-group">
        <el-button type="primary" @click="openAddDialog" class="add-btn">
          <el-icon><Plus /></el-icon>新增科室
        </el-button>
        <el-button @click="refreshData" class="refresh-btn">
          <el-icon><Refresh /></el-icon>刷新数据
        </el-button>
      </div>
    </div>

    <!-- 3. 加载状态 -->
    <el-skeleton v-if="loading" :loading="loading" animated :rows="10" />
    
    <!-- 4. 数据表格 -->
    <el-table
      v-else
      :data="pagedData"
      row-key="departmentId"
      border
      stripe
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      v-loading="tableLoading"
    >
      <!-- 各列定义 -->
      <el-table-column label="序号" width="80" align="center">
        <!-- 一级科室加粗显示 -->
        <template #default="scope">
          <span v-if="scope.row.level === 1" style="font-weight: bold;">{{ scope.$index + 1 + (currentPage - 1) * pageSize }}</span>
          <span v-else style="padding-left: 20px;">{{ scope.$index + 1 + (currentPage - 1) * pageSize }}</span>
        </template>
      </el-table-column>
      
      <!-- 科室名称(带搜索高亮) -->
      <el-table-column prop="departmentName" label="科室名称" align="center">
        <template #default="{row}">
          <span v-html="highlightSearchText(row.departmentName)"></span>
        </template>
      </el-table-column>
      
      <!-- 科室层级(用标签显示) -->
      <el-table-column prop="level" label="层级" align="center" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.level === 1 ? 'primary' : 'success'">
            {{ scope.row.level === 1 ? '一级' : '二级' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <!-- 父级科室(二级科室显示) -->
      <el-table-column prop="parentId" label="父级科室" align="center" width="120">
        <template #default="scope">
          {{ scope.row.level === 1 ? '无' : getParentName(scope.row.parentId) }}
        </template>
      </el-table-column>
      
      <!-- 创建时间(格式化显示) -->
      <el-table-column prop="createTime" label="创建时间" align="center" width="180">
        <template #default="{row}">
          {{ formatCreateTime(row.createTime) }}
        </template>
      </el-table-column>
      
      <!-- 操作列(编辑/删除按钮) -->
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button size="small" @click.stop="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 5. 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="filteredDepartments.length"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 6. 空状态提示 -->
    <el-empty v-if="!loading && departmentList.length === 0" description="暂无科室数据" />
    
    <!-- 7. 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 科室名称输入 -->
        <el-form-item label="科室名称" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入科室名称" />
        </el-form-item>
        
        <!-- 科室层级选择(新增时显示) -->
        <el-form-item label="科室层级" prop="level" v-if="!isEdit">
          <el-radio-group v-model="form.level" @change="handleLevelChange">
            <el-radio :label="1">一级科室</el-radio>
            <el-radio :label="2">二级科室</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 父级科室选择(二级科室时显示) -->
        <el-form-item label="父级科室" prop="parentId" v-if="form.level === 2">
          <el-select 
            v-model="form.parentId" 
            placeholder="请选择父级科室"
            filterable
            clearable
          >
            <el-option 
              v-for="dept in parentDepartments" 
              :key="dept.departmentId" 
              :label="dept.departmentName" 
              :value="dept.departmentId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { Refresh, Plus, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 加载状态
const loading = ref(false);        // 控制页面初始加载状态
const tableLoading = ref(false);   // 控制表格加载状态(如删除、刷新时)
const submitLoading = ref(false);  // 控制表单提交按钮的加载状态

// 数据相关状态
const departmentList = ref([]);    // 存储从后端获取的所有科室数据
const parentDepartments = ref([]); // 只存储一级科室(用于二级科室的父级选择)

// 对话框相关状态
const dialogVisible = ref(false);  // 控制新增/编辑对话框的显示
const isEdit = ref(false);         // 标识当前是编辑模式(false为新增模式)

// 搜索与分页状态
const searchKey = ref('');         // 搜索关键词
const currentPage = ref(1);        // 当前页码
const pageSize = ref(10);          // 每页显示数量

// 表单数据
const form = ref({
  departmentId: null,     // 科室ID(新增时为null)
  departmentName: '',     // 科室名称
  level: 1,               // 科室层级(1-一级科室,2-二级科室)
  parentId: null          // 父级科室ID(二级科室时需要)
});

// 表单验证规则
const rules = {
  departmentName: [
    { required: true, message: '请输入科室名称', trigger: 'blur' }, // 必填验证
    { min: 2, max: 50, message: '科室名称长度在2-50个字符之间', trigger: 'blur' } // 长度验证
  ],
  level: [
    { required: true, message: '请选择科室层级', trigger: 'change' } // 必选验证
  ],
  parentId: [
    { 
      // 自定义验证规则:二级科室必须选择父级科室,当科室层级(level)为2(二级科室)且父级ID(value)为空时，验证失败,其他情况验证通过
      validator: (rule, value, callback) => {
        if (form.value.level === 2 && !value) {
          callback(new Error('二级科室必须选择父级科室'));
        } else {
          callback();
        }
      }, 
      trigger: 'change' 
    }
  ]
};

// 计算属性
// 对话框标题(根据编辑/新增模式变化)
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑科室' : '新增科室';
});

// 过滤后的科室数据(根据搜索关键词)
const filteredDepartments = computed(() => {
  if (!searchKey.value) return buildTree(departmentList.value); // 无搜索词返回完整树
  
  // 有搜索词时过滤
  const searchTerm = searchKey.value.toLowerCase();
  const filtered = departmentList.value.filter(dept => 
    dept.departmentName.toLowerCase().includes(searchTerm)
  );
  return buildTree(filtered); // 将过滤结果构建为树形结构
});

// 当前页的数据(分页处理)
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredDepartments.value.slice(start, end); // 返回当前页的数据切片
});

// 构建树形结构
const buildTree = (departments) => {
  const map = {};    // 用对象存储所有科室(便于快速查找)
  const roots = [];  // 存储一级科室(树根)
  
  // 1. 初始化所有节点
  departments.forEach(dept => {
    map[dept.departmentId] = { ...dept, children: [] }; // 复制科室并添加children属性
  });
  
  // 2. 构建父子关系
  departments.forEach(dept => {
    if (dept.level === 2 && map[dept.parentId]) {
      // 如果是二级科室且能找到父级，则添加到父级的children中
      map[dept.parentId].children.push(map[dept.departmentId]);
    } else if (dept.level === 1) {
      // 一级科室直接作为根节点
      roots.push(map[dept.departmentId]);
    }
  });
  
  return roots; // 返回树形结构
};

// 格式化日期
const formatCreateTime = (time) => {
  if (!time) return '';
  try {
    return new Date(time).toLocaleString();
  } catch (e) {
    return time;
  }
};

// 高亮搜索文本
const highlightSearchText = (text) => {
  if (!searchKey.value || !text) return text;
  const regex = new RegExp(searchKey.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
  return text.replace(regex, match => 
    `<span style="color: #409eff; font-weight: bold;">${match}</span>`
  );
};

// 获取父级科室名称,比较科室ID与传入的parentId
const getParentName = (parentId) => {
  const parent = departmentList.value.find(dept => dept.departmentId === parentId);
  return parent ? parent.departmentName : '未知';
};

// 获取科室数据
// 从后端获取科室数据
const fetchData = async () => {
  loading.value = true;        // 显示全局加载状态
  tableLoading.value = true;   // 显示表格加载状态
  
  try {
    // 发送GET请求获取数据
    const response = await axios.get('http://localhost:8080/hospital5_war/department/findAll');
    departmentList.value = response.data || []; // 存储原始数据
    
    // 提取一级科室作为父级选项
    parentDepartments.value = departmentList.value.filter(dept => dept.level === 1);
  } catch (error) {
    console.error('获取科室数据失败:', error);
    // 显示错误提示
    ElMessage.error('获取科室数据失败，请稍后重试');
  } finally {
    loading.value = false;
    tableLoading.value = false;
  }
};


// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

const handleSearchClear = () => {
  searchKey.value = '';
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false;
  form.value = {
    departmentId: null,
    departmentName: '',
    level: 1,
    parentId: null
  };
  dialogVisible.value = true;
};

// 处理层级变化
const handleLevelChange = (val) => {
  if (val === 1) {
    form.value.parentId = null;
  }
};

// 打开编辑对话框
const openEditDialog = (row) => {
  isEdit.value = true;
  form.value = {
    departmentId: row.departmentId,
    departmentName: row.departmentName,
    level: row.level,
    parentId: row.parentId || null
  };
  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      if (isEdit.value) {
        await updateDepartment();
      } else {
        await addDepartment();
      }
      dialogVisible.value = false;
      refreshData();
    } catch (error) {
      console.error('操作失败:', error);
    } finally {
      submitLoading.value = false;
    }
  });
};

// 新增科室
const addDepartment = async () => {
  try {
    await axios.post('http://localhost:8080/hospital5_war/department/addDepartment', form.value);
    ElMessage.success('新增科室成功');
  } catch (error) {
    console.error('新增科室失败:', error);
    ElMessage.error(error.response?.data?.message || '新增科室失败，请稍后重试');
    throw error;
  }
};

// 更新科室
const updateDepartment = async () => {
  try {
    await axios.post('http://localhost:8080/hospital5_war/department/updateDepartment', form.value);
    ElMessage.success('更新科室成功');
  } catch (error) {
    console.error('更新科室失败:', error);
    if (error.response?.status === 404) {
      ElMessage.error('未找到对应科室');
    } else {
      ElMessage.error(error.response?.data?.message || '更新科室失败，请稍后重试');
    }
    throw error;
  }
};

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除科室【${row.departmentName}】吗？${
        row.level === 1 && row.children?.length > 0 
          ? '该科室下有子科室，删除后将一并删除！' 
          : ''
      }`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    tableLoading.value = true;
    await axios.delete(`http://localhost:8080/hospital5_war/department/deleteDepartment/${row.departmentId}`);
    ElMessage.success('删除科室成功');
    refreshData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除科室失败:', error);
      if (error.response?.status === 404) {
        ElMessage.error('未找到对应科室');
      } else {
        ElMessage.error(error.response?.data?.message || '删除科室失败，请稍后重试');
      }
    }
  } finally {
    tableLoading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  currentPage.value = 1;
  fetchData();
};

// 处理对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 初始化加载数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.doctor-department {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  margin: 0;
  margin-left: 10px;
  font-size: 18px;
  font-weight: 500;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.add-btn {
  background-color: #f0f7ff;
  border-color: #c6e2ff;
  color: #409eff;
}

.add-btn:hover {
  background-color: #d9ecff;
}

.refresh-btn {
  background-color: #f4f4f5;
  border-color: #d3d4d6;
  color: #909399;
}

.refresh-btn:hover {
  background-color: #e9e9eb;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格样式调整 */
.el-table {
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}
</style>